package user.controllers;

import helpers.PaginatorHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import user.models.ArticleModel;
import user.models.CategoryModel;

import debugs.UserDebug;

import entities.ApplicationConfig;
import entities.Article;
import entities.Category;
import entities.User;

public class ArticleListServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		User author = (User) request.getAttribute("user_logged_in");
		
		if (author == null) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		//Get article by author and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 20;
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = articleModel.listByMyArticle(appConfig.getApplicationId(), author.getId(), page, limit, language);
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		//Get categories
		List<String> cIds = new ArrayList<String>();
		
		for (int i = 0; i < articles.size(); i++) {
			if (!articles.get(i).getCategory().isEmpty()) {
				cIds.add(articles.get(i).getCategory());
			}
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Map<String, Category> categories = categoryModel.getByListId(appConfig.getApplicationId(), cIds);
		
		request.setAttribute("author", author);
		request.setAttribute("user", author);
		request.setAttribute("articles", articles);
		request.setAttribute("categories", categories);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher("/user/pages/article_list.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
